package cn.infomany;

import cn.infomany.bean.ErrorInfo;
import org.antlr.v4.runtime.BaseErrorListener;
import org.antlr.v4.runtime.Parser;
import org.antlr.v4.runtime.RecognitionException;
import org.antlr.v4.runtime.Recognizer;

import java.util.Collections;
import java.util.List;


public class SyntaxErrorListener extends BaseErrorListener {

    private boolean errorOccurred;
    private ErrorInfo errorInfo;


    @Override
    public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol,
                            int line, int charPositionInLine,
                            String msg, RecognitionException e) {
        errorOccurred = true;
        List<String> ruleInvocationStack = ((Parser) recognizer).getRuleInvocationStack();
        Collections.reverse(ruleInvocationStack);

        errorInfo = new ErrorInfo(offendingSymbol, line, charPositionInLine, msg);


        System.err.println("[语法错误] ruleInvocationStack: " + ruleInvocationStack);
        System.err.println("行" + line + "列" + charPositionInLine + "非法符号: " + offendingSymbol + ". 原始原因:" + msg);
    }

    public boolean isErrorOccurred() {
        return errorOccurred;
    }

    public ErrorInfo getErrorInfo() {
        return errorInfo;
    }
}